<template>
  <div class="login-container">
    <div class="login-box">
      <div class="project-name">
        <h1>lifeRecordBms</h1>
      </div>
      <div class="login-header">
        <h2>{{ isLogin ? '用户登录' : '用户注册' }}</h2>
        <p>{{ isLogin ? '欢迎回来，请登录您的账户' : '创建新账户' }}</p>
      </div>

      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          class="login-form"
          @submit.prevent="handleSubmit"
      >
        <!-- 账号 -->
        <el-form-item prop="account">
          <el-input
              v-model="form.account"
              placeholder="请输入账号"
              prefix-icon="User"
              size="large"
              clearable
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              size="large"
              show-password
              @keyup.enter="handleSubmit"
          />
        </el-form-item>

        <!-- 注册时需要填写的字段 -->
        <template v-if="!isLogin">
          <el-form-item prop="confirmPassword">
            <el-input
                v-model="form.confirmPassword"
                type="password"
                placeholder="请确认密码"
                prefix-icon="Lock"
                size="large"
                show-password
                @keyup.enter="handleSubmit"
            />
          </el-form-item>
        </template>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              size="large"
              class="submit-btn"
              :loading="loading"
              @click="handleSubmit"
              block
          >
            {{ isLogin ? '登录' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 切换登录/注册 -->
      <div class="toggle-form">
        <span>
          {{ isLogin ? '还没有账户？' : '已有账户？' }}
          <el-button type="text" @click="toggleForm">
            {{ isLogin ? '立即注册' : '立即登录' }}
          </el-button>
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { login, addUser } from '@/api/modules/user'
import { useRouter } from 'vue-router'
import websocket from '@/utils/websocket'

// 定义表单数据
const form = reactive({
  account: '',
  password: '',

  confirmPassword: ''
})

// 表单引用
const formRef = ref<FormInstance | null>(null)

// 加载状态
const loading = ref(false)

// 登录/注册切换
const isLogin = ref(true)

// router实例
const router = useRouter()

// 切换表单
const toggleForm = () => {
  isLogin.value = !isLogin.value
  // 清空表单验证
  formRef.value?.clearValidate()
}

// 定义表单验证规则
const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 20, message: '账号长度应在2-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 20, message: '密码长度应在1-20个字符之间', trigger: 'blur' }
  ],

  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!isLogin.value && value !== form.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true

      if (isLogin.value) {
        // 登录逻辑
        await handleLogin()
      } else {
        // 注册逻辑
        await handleRegister()
      }
      
      loading.value = false
    }
  })
}

// 登录
const handleLogin = async () => {
  try {
    const response = await login({
      account: form.account,
      password: form.password
    })
    
    ElMessage.success('登录成功')
    localStorage.setItem('user', JSON.stringify(response.data.user))
    
    // 初始化WebSocket连接
    websocket.init(response.data.user.user_id)
    
    // 跳转到首页
    router.push('/home')
  } catch (err: any) {
    console.error('登录失败:', err)
    // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
  }
}

// 注册
const handleRegister = async () => {
  try {
    // 先注册用户
    const response = await addUser({
      account: form.account,
      password: form.password
    })
    
    ElMessage.success('注册成功')
    
    // 注册成功后直接登录
    const loginResponse = await login({
      account: form.account,
      password: form.password
    })
    
    ElMessage.success('登录成功')
    localStorage.setItem('user', JSON.stringify(loginResponse.data.user))
    
    // 初始化WebSocket连接
    websocket.init(loginResponse.data.user.user_id)
    
    // 跳转到首页
    router.push('/home')
  } catch (err: any) {
    console.error('注册失败:', err)
    // 错误信息已经在request.ts的响应拦截器中处理过了，这里不需要再显示
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('@/assets/login_bg.jpg') no-repeat center center;
  background-size: cover;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 40px 30px;
  backdrop-filter: blur(10px);
}

.project-name {
  text-align: center;
  margin-bottom: 20px;
}

.project-name h1 {
  margin: 0;
  font-size: 32px;
  color: #409EFF;
  font-weight: 700;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-bottom: 20px;
}

.submit-btn {
  margin-top: 10px;
}

.toggle-form {
  text-align: center;
  color: #666;
  font-size: 14px;
}

.toggle-form .el-button {
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-box {
    padding: 30px 20px;
  }

  .project-name h1 {
    font-size: 28px;
  }

  .login-header h2 {
    font-size: 22px;
  }
}
</style>